package LintCode;

import javax.xml.stream.events.StartDocument;
import java.util.*;

/**
 * @Classname IntersectionOfTwoArrays
 * @Description TODO
 * @Date 2021/3/4 18:25
 * @Created by ASUS
 */
public class IntersectionOfTwoArrays {
    /**
     * @param nums1: an integer array
     * @param nums2: an integer array
     * @return: an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // write your code here
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int i : nums1) {
            set1.add(i);
        }
        for (int i : nums2) {
            set2.add(i);
        }

        set1.retainAll(set2);
        int[] ans = new int[set1.size()];
        int index = 0;
        for (int an : set1) {
            ans[index++] = an;
        }
        return ans;
    }

    public static int[] f(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) return null;
        if (nums2.length > nums1.length) return f(nums2, nums1);
        List<Integer> ansList = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            if (i == 0) map.put(nums1[i], 0);
            else if (nums1[i - 1] != nums1[i]) map.put(nums1[i], 0);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (i == 0) {
                if (map.containsKey(nums2[i])) {
                    ansList.add(nums2[i]);
                    map.put(nums2[i], 1);
                }
            } else {
                if (nums2[i - 1] != nums2[i]) {
                    if (map.containsKey(nums2[i]) && map.get(nums2[i]) != 0) {
                        ansList.add(nums2[i]);
                        map.put(nums2[i], 1);
                    }
                }
            }
        }
        return ansList.stream().mapToInt(Integer::valueOf).toArray();
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new IntersectionOfTwoArrays().intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
    }
}
